package com.lsa.shenn.chap2;

import com.lsa.helpers.Utils;
import com.lsa.shenn.common.*;

public class Task_2_1_4 implements Task
{
	private int k;
	private boolean isZeroBased;
	
	public Task_2_1_4(int k, boolean isZeroBased)
	{
		super();
		this.k = k;
		this.isZeroBased = isZeroBased;
	}

	public void doIt()
	{
		int[] seq = createFirstSequence();
		do
		{
			Utils.print(seq);
			seq = move2NextSequence(seq);
		}
		while(seq != null);
	}
	
	public int[] createFirstSequence()
	{
		int[] seq = new int[this.k];
		for (int i = 0; i < seq.length; i++)
		{
			seq[i] = isZeroBased ? 0 : 1;
		}
		
		return seq;
	}
	
	public int[] move2NextSequence(int[] seq)
	{
		boolean isChanged = false;
		
		int i = seq.length - 1;
		
		for (; i > -1; i--)
		{
			if (seq[i] < (isZeroBased ? i : i + 1))
			{
				seq[i]++;
				isChanged = true;
				break;
			}
		}
		
		if (isChanged)
		{
			i++;
			
			for (; i < seq.length; i++)
			{
				seq[i] = isZeroBased ? 0 : 1;
			}
		}
		
		return isChanged? seq : null;
	}
}
